<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange"
			highlight-current-row style="width: 100%;">
			<!-- highlight-current-row style="width: 100%;" @row-dblclick="handleRowDblClick"> -->
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="70" label="编号">
			</el-table-column>
			<el-table-column label="数据字典名" width="120">
				<template #default="scope">
					<!-- 给字典名文本绑定双击事件，传递当前行数据 -->
					<span @dblclick="handleDictNameDblClick(scope.row)"
						style="display: inline-block; width: 100%; padding: 8px;">
						{{ scope.row.dictName }}
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="120">
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[5, 10, 15]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>
		<!--添加或修改界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="字典名" prop="dictName">
					<el-input v-model="saveForm.dictName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="字典编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>

		<el-drawer title="数据字典明细" :visible.sync="drawerVisible" direction="rtl" size="60%"
			:before-close="handleDrawerClose">
			<!-- 明细查询区 -->
			<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
				<el-form :inline="true">
					<el-form-item>
						<el-input v-model="itemKeyword" placeholder="明细名称/值"></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="warning" @click="itemQuery">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleAddItem">新增明细</el-button>
					</el-form-item>
				</el-form>
			</el-col>

			<!-- 明细列表 -->
			<el-table :data="itemTableData" v-loading="itemListLoading" style="width: 100%;">
				<el-table-column type="index" label="序号" width="70"></el-table-column>
				<el-table-column prop="itemName" label="明细名称" width="180"></el-table-column>
				<el-table-column prop="itemValue" label="明细值" width="180"></el-table-column>
				<el-table-column label="操作">
					<template #default="scope">
						<el-button size="small" @click="handleEditItem(scope.row)">编辑</el-button>
						<el-button type="danger" size="small" @click="handleDelItem(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 明细分页 -->
			<el-col :span="24" class="toolbar" style="margin-top: 10px;">
				<el-pagination @size-change="handleItemSizeChange" @current-change="handleItemCurrentChange"
					:current-page="itemCurrentPage" :page-sizes="[5, 10, 15]" :page-size="itemPageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="itemTotal"
					style="float: right;"></el-pagination>
			</el-col>

			<!-- 明细新增/编辑弹窗 -->
			<el-dialog :title="itemTitle" :visible.sync="itemSaveVisible" :close-on-click-modal="false" append-to-body>
				<el-form :model="itemForm" label-width="80px" :rules="itemRules" ref="itemFormRef">
					<el-form-item label="明细名称" prop="itemName">
						<el-input v-model="itemForm.itemName"></el-input>
					</el-form-item>
					<el-form-item label="明细值" prop="itemValue">
						<el-input v-model="itemForm.itemValue"></el-input>
					</el-form-item>
				</el-form>
				<template slot="footer" class="dialog-footer">
					<el-button @click="itemSaveVisible = false">取消</el-button>
					<el-button type="primary" @click="itemSubmit">提交</el-button>
				</template>
			</el-dialog>
		</el-drawer>
	</section>
</template>

<script>

export default {
	data() {
		return {
			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			listLoading: false,
			//2.高级查询相关数据
			keyword: '',
			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录

			//5.添加和修改相关数据
			saveFormVisible: false,
			saveForm: {
				id: null,
				dictName: '',
				sn: ''
			},
			title: '',
			//6.添加和修改校验规则-表单项校验
			// 明细抽屉相关状态
			drawerVisible: false,       // 抽屉是否显示
			currentDictId: null,       // 当前关联的字典ID（双击主表行时赋值）
			itemKeyword: '',           // 明细查询关键字
			itemTableData: [],         // 明细列表数据
			itemTotal: 0,              // 明细总条数
			itemCurrentPage: 1,        // 明细当前页
			itemPageSize: 5,           // 明细每页条数
			itemListLoading: false,    // 明细加载状态

			// 明细新增/编辑弹窗
			itemSaveVisible: false,    // 弹窗是否显示
			itemTitle: '',             // 弹窗标题（新增/编辑）
			itemForm: {                // 明细表单数据
				id: null,
				itemName: '',
				itemValue: '',
				dictId: null  // 关联的字典ID，双击时自动赋值
			},
			saveFormRules: {
				// userName: [
				// 	{ required: true, message: '请输入用户名称', trigger: 'blur' }
				// ],
				// phone: [
				// 	{ required: true, message: '请输入电话号码', trigger: 'blur' }
				// ],
				// password: [
				// 	{ required: true, message: '请输入登录密码', trigger: 'blur' }
				// ]
				itemName: [{ required: true, message: '请输入明细名称', trigger: 'blur' }],
				itemValue: [{ required: true, message: '请输入明细值', trigger: 'blur' }]
			},


		}
	},
	methods: {
		handleDictNameDblClick(row) {
			this.currentDictId = row.id; // 记录当前字典ID
			this.drawerVisible = true;   // 打开抽屉
			this.itemCurrentPage = 1;    // 重置页码
			this.getItemData();          // 加载明细数据
		}
		, getItemData() {
			this.itemListLoading = true;
			const param = {
				currentPage: this.itemCurrentPage,
				pageSize: this.itemPageSize,
				keyword: this.itemKeyword,
				dictId: this.currentDictId
			};
			this.$http.post('/dictItem', param).then((res) => {
				// 1. 初始化默认值，避免后续操作报错
				this.itemTableData = [];
				this.itemTotal = 0;

				// 2. 检查后端返回是否正常
				if (!res || !res.data) {
					console.error('后端返回数据格式异常：', res);
					this.itemListLoading = false;
					return;
				}

				// 3. 确保 list 是数组
				const rawList = res.data.list;
				if (!Array.isArray(rawList)) {
					console.warn('res.data.list 不是数组，已自动转为空数组', rawList);
					this.itemListLoading = false;
					return;
				}

				// 4. 处理数组中的无效项并深拷贝
				this.itemTableData = res.data.list.map(item => Object.assign({}, item));
				// 5. 处理总条数（确保是数字）
				this.itemTotal = typeof res.data.total === 'number' ? res.data.total : 0;

				this.itemListLoading = false;
			}).catch((err) => {
				console.error('获取明细数据失败：', err);
				this.$message.error('获取明细数据失败，请稍后重试！');
				this.itemListLoading = false;
			});
		},// 3. 明细查询（关键字搜索）
		itemQuery() {
			this.itemCurrentPage = 1;
			this.getItemData();
		},

		// 4. 明细分页：切换页码
		handleItemCurrentChange(currentPage) {
			this.itemCurrentPage = currentPage;
			this.getItemData();
		},

		// 5. 明细分页：切换每页条数
		handleItemSizeChange(pageSize) {
			this.itemPageSize = pageSize;
			this.itemCurrentPage = 1; // 切换条数后重置页码
			this.getItemData();
		},
		//7. 明细新增
		handleAddItem() {
			this.itemForm = {
				dictId: this.currentDictId, // 自动关联当前字典ID
				itemName: '',
				itemValue: ''
			};
			this.itemTitle = '新增明细';
			this.itemSaveVisible = true;
		},
		handleEditItem(row) {
			// 1. 深拷贝行数据（避免浅拷贝导致表格数据被联动修改）
			this.itemForm = JSON.parse(JSON.stringify(row));
			// 3. 设置弹窗标题并显示
			this.itemTitle = '修改明细';
			this.itemSaveVisible = true;
			//清除缓存
		},
		//8.删除明细
		handleDelItem(row) {
			this.$confirm('此操作将永久删除该明细，是否继续？', '警告', {
				type: 'warning'
			}).then(() => {
				this.$http.delete("/dictItem/" + row.id).then((res) => {
					if (res.data.success) {
						this.$message.success(res.data.msg);
						this.getItemData(); // 删除后重新加载明细
					} else {
						this.$message.error(res.data.msg);
					}
				}).catch(() => {
					this.$message.error('服务器繁忙，请稍后重试！');
				});
			}).catch(() => {
				this.$message.info('已取消删除');
			});
		},
		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
			this.listLoading = true;
			let param = {
				currentPage: this.currentPage,
				pageSize: this.pageSize,
				keyword: this.keyword
			};
			this.$http.post('/dict', param).then((res) => {
				console.log(res);
				this.tableDatas = res.data.list;
				this.totals = res.data.total;
				this.listLoading = false;
			}).catch((res) => {
				this.$message.error('服务器繁忙，请稍后再试！');
			});
		},
		//1.2.选择第几页时触发
		handleCurrentChange(currentPage) {
			this.currentPage = currentPage;
			this.getTableData();
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.getTableData();
		},
		//2.高级查询相关方法
		keywordQuery() {
			this.currentPage = 1;
			this.getTableData();
		},
		//3.删除相关方法
		handleDel(row) {
			this.$confirm('此操作将永久删除该用户，是否继续？', '删除', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.delete("/dict/" + row.id).then((res) => {
					console.log(res);
					if (res.data.success) {
						this.$message.success(res.data.msg);
						this.getTableData();
					} else {
						this.$message.error(res.data.msg);
					}
				}).catch(() => {
					this.$message.error("服务器繁忙....");
				});
			}).catch(() => {
				this.$message.info("已取消删除");
			});
		},
		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
			console.log(val);
			//传入的参数是选中的行的数据,行的数组,我们要从这个数组获取id,得到一个id数组[1,2,3,4]
			this.sels = val.map(row => row.id);//!!!数组的map映射!!!
			console.log(this.sels);
		},
		//4.2.批量删除
		handlePatchDel() {
			this.$confirm('此操作将批量删除这些用户，是否继续？', '删除', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.patch("/dict", this.sels).then(res => {
					if (res.data.success) {
						this.$message.success(res.data.msg);
						this.currentPage = 1;
						this.getTableData();
					} else {
						this.$message.error(res.data.msg);
					}
				}).catch(() => {
					this.$message.error(res.data.msg);
				});
			}).catch(() => {
				this.$message.info("已取消删除");
			});
		},
		//5.添加和修改相关方法
		//5.1.点击添加弹出对话框
		handleAdd() {
			this.saveForm = {};
			this.title = "新增";
			this.saveFormVisible = true;
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
			this.saveForm = Object.assign({}, row);
			this.title = "修改";
			this.saveFormVisible = true;
		},
		//5.3.提交表单数据操作数据库
		saveSubmit() {
			this.$refs["saveForm"].validate((valid) => {//判断校验是否通过
				if (valid) {
					//1.点击提交,saveForm已经有值,双向绑定的,直接发送保存的异步请求
					this.$http.put("/dict", this.saveForm).then(res => {
						//console.log(res);
						if (res.data.success) {//保存成功
							//1.提示操作成功
							this.$message.success(res.data.msg);
							//2.关闭对话框
							this.saveFormVisible = false;
							//3.1如果是新增,则跳转到最后一页
							if (this.saveForm.id == null) {//新增
								//3.2 新增多了一条,所以改变总条数,触发重新计算总页数!!!	
								this.totals = this.totals + 1;
								//3.3赋值最后一页
								this.currentPage = Math.ceil(this.totals / this.pageSize);//页码重新赋值
							}
							//修改停留在当前页,默认就是当前页,所以不用操作,重新查询列表数据即可↓
							//重新查询数据
							this.getTableData();
						} else {//保存失败
							this.$message.error(res.data.msg);
						}
					}).catch(() => {
						this.$message.error("网络异常，请稍后重试！【400/404/...】");
					})
				} else {
					this.$message.error("校验不通过,必填项没有内容");
					return false;
				}
			});
		},
		itemSubmit() {
			this.$refs.itemFormRef.validate((valid) => {
				if (valid) {
					// 区分新增（无id）和编辑（有id）
					const url = '/dictItem';
					this.$http.put(url, this.itemForm).then((res) => {
						if (res.data.success) {
							this.$message.success(res.data.msg);
							this.itemSaveVisible = false;
							// 新增后刷新明细列表，若为新增且分页在最后一页，自动加载最新页
							if (!this.itemForm.id) {
								// 计算新增后是否需要切换到最后一页
								const totalAfterAdd = this.itemTotal + 1;
								const lastPage = Math.ceil(totalAfterAdd / this.itemPageSize);
								this.itemCurrentPage = lastPage; // 跳转到最后一页
							}
							this.getItemData(); // 刷新明细列表
						} else {
							this.$message.error(res.data.msg);
						}
					}).catch(() => {
						this.$message.error('网络异常，请稍后重试！');
					});
				} else {
					this.$message.error('表单校验失败，请检查必填项！');
					return false; // 阻止提交
				}
			});
		}

	},
	mounted() {
		this.getTableData();
	}
}
</script>
<style scoped></style>
